package com.apimarket.util.net;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * POST请求
 */
public class PostNetContext extends NetContext {

    private CloseableHttpClient client;

    private HttpPost httpPost;

    public PostNetContext(String url, Map<String, Object> params) {
        super(url, params);
        this.client = HttpClients.createDefault();
        this.httpPost = new HttpPost(getUrl());
    }

    private CloseableHttpResponse getResponse() throws IOException {
        Map<String, Object> tmp = getParams();
        if (tmp != null && tmp.size() != 0) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<String> keys = tmp.keySet();
            Iterator<String> iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                nvps.add(new BasicNameValuePair(key, tmp.get(key).toString()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }

        return client.execute(httpPost);
    }

    @Override
    public JsonNode getResultJson() throws IOException {
        try (CloseableHttpResponse response = getResponse()) {
            HttpEntity entity = response.getEntity();
            String jsonStr = getJsonStr(entity);
            EntityUtils.consume(entity);
            return new ObjectMapper().readTree(jsonStr);
        }
    }
}
